import turtle
import random
import simpleaudio as sa

# 音效
laser = sa.WaveObject.from_wave_file('./audio/laser.wav')
exp = sa.WaveObject.from_wave_file('./audio/explosion.wav')

game = turtle.Screen()
game.setup(700,700) # 设置窗口大小
game.title('太空侵略者') # 游戏标题
game.bgpic('./img/bg.gif') # 大背景图片

turtle.addshape('./img/player.gif')
player = turtle.Turtle() #创建玩家
player.ht() #隐藏线条
player.speed(0) #速度
player.up()
player.shape('./img/player.gif') #使用自定义图标
player.setpos(0,-300) #设置初始位置
player.st()

player_step = 15;

# 设置移动函数 左边
def go_left():
    x = player.xcor()
    x = x - player_step
    if x < -300:
        x = -300
    player.setx(x)
# 右边
def go_right():
    x = player.xcor()
    x = x + player_step
    if x > 300:
        x = 300
    player.setx(x)
    
#发射子弹
is_fire = False
def fire():
    global is_fire
    if is_fire == False:
        bomb.setpos(player.xcor(),player.ycor()+20)
        bomb.st()
        is_fire = True
        laser.play()

#监听输入
turtle.listen()
turtle.onkey(go_left,'Left')
turtle.onkey(go_right,'Right')
turtle.onkey(fire,'space')

#添加子弹
bomb = turtle.Turtle()
bomb.ht()
bomb.speed(0)
bomb.up()
bomb.shape('triangle')
bomb.color('yellow')
bomb.shapesize(0.5,0.5)
bomb.seth(90)
#添加分数
score = 0
pen = turtle.Turtle()
pen.color('white')
pen.speed(0)
pen.up()
pen.ht()
pen.setpos(-340,230)
score_string = "分数:%s" %score
pen.write(score_string,align="left",font=('Ariai',12,'normal'))


#创建敌人
turtle.addshape('./img/inv.gif')
num = 6
inv_list = []
for i in range(6):
    inv = turtle.Turtle()
    inv_list.append(inv)
    inv.ht()
    inv.speed(0)
    inv.up()
    inv.shape('./img/inv.gif')
    x = random.randint(-200,200)
    y = random.randint(100,220)
    inv.setpos(x,y)
    inv.st()



#敌人动起来
inv_step = 2
bomb_step = 20
score_step = 10
go_back = False
game_over = False
while True:
    if game_over:
        pen_to = turtle.Turtle()
        pen_to.color('red')
        pen_to.ht()
        pen_to.write('游戏结束',align='center',font=('Ariai',24,'normal'))
        exp.play()
        break
    for inv in inv_list:
        x = inv.xcor()
        x += inv_step
        inv.setx(x)
        if x > 300 or x < -300:
            go_back = True
        if inv.distance(bomb) < 15:
            inv.setpos(0,240)
            is_fire = False
            bomb.setpos(-350,-350)
            bomb.ht()
            score += score_step
            score_string = "分数:%s" %score
            pen.clear()
            pen.write(score_string,align="left",font=('Ariai',12,'normal'))
            exp.play()
        if inv.ycor() < -280:
            game_over = True
            
    if go_back:
        inv_step *= -1
        go_back = False
        for inv in inv_list:
            y = inv.ycor()
            y -= 40
            inv.sety(y)

    if is_fire:
        y = bomb.ycor()
        y += bomb_step
        bomb.sety(y)
        if y > 250:
            is_fire = False
            bomb.setpos(-350, -350)
            bomb.ht()
    
